package com.pc.fqueue.util;

import com.pc.fqueue.exception.ConfigException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;


public class Config {
	private final static Log log = LogFactory.getLog(Config.class);
	// map 存储配置信息
	private static Map<String, String> setting = new ConcurrentHashMap<String, String>();
	
	private static File file = new ConfigLocation().getFile();
	
	// 调用初始化操作
	static {
		iniSetting();
	}

	public Config() {
		
	}


	public static synchronized void iniSetting() {
		/*File file;
		file = new File("config.properties");
		System.out.println(file.getAbsolutePath());		
		if (!file.exists()) {
			iniSetting("config/config.properties");
		} else {
			iniSetting("config.properties");
		}*/
		iniSetting(null);
	}

	/**
	 * 初始化加载配置文件
	 * 
	 * @param path
	 *            加载路径
	 * @throws java.io.FileNotFoundException
	 */
	public static synchronized void iniSetting(String path) {
		//File file;
		//file = new File(path);
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			Properties p = new Properties();
			p.load(in);
			// 遍历配置文件加入到Map中进行缓存
			Enumeration<?> item = p.propertyNames();
			while (item.hasMoreElements()) {
				String key = (String) item.nextElement();
				setting.put(key, p.getProperty(key));
			}
			in.close();
		} catch (FileNotFoundException e) {
			//log.error("config file not found at" + file.getAbsolutePath());
			log.error("config file not found");
			throw new ConfigException("FileNotFoundException", e);
		} catch (IOException e) {
			//log.error("config file not found at" + file.getAbsolutePath());
			log.error("config file not found");
			throw new ConfigException("IOException", e);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ConfigException("Exception", e);
		} finally {
			if(in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void reload() {
		try {
			iniSetting();
		} catch (ConfigException e) {
			throw new ConfigException(e.getMessage(), e);
		}
	}

	/**
	 * 获取配置文件的某个键值的配置信息
	 * 
	 * @param key
	 *            键
	 * @return 值
	 */
	public static String getSetting(String key) {
		return setting.get(key);
	}

	/**
	 * 设置配置文件的数据
	 * 
	 * @param key
	 * @param value
	 */
	public static void setSetting(String key, String value) {
		setting.put(key, value);
	}

	public static int getInt(String key) {
		return Integer.parseInt(setting.get(key));
	}
}
